<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { saveMenu, getMenuById, selectParentMenu } from '@/api/system/authority'
import { useEmitt } from '@/hooks/web/useEmitt'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Check, Close } from '@element-plus/icons-vue'
import { useI18n } from '@/hooks/web/useI18n'
import { getZhHKAndPinyin, getZhCNAndPinyin } from '@/api/common'
import { getCurUser } from '@/utils'
import { useLocaleStore } from '@/store/modules/locale'

defineOptions({
  name: 'MenuEdit'
})

const { t } = useI18n()
const { emitter } = useEmitt()
const formRef = ref()
const { currentRoute } = useRouter()
const user = getCurUser() as any
const localeStore = useLocaleStore()

const state = reactive({
  // 表单数据
  formData: {
    id: null,
    menuId: '',
    menuName: '',
    enName: '',
    hkName: '',
    parentId: null,
    url: '',
    component: '',
    params: '',
    navUrl: '',
    icon: '',
    sort: 1,
    menuType: 1,
    frontType: 1,
    tenantId: user.tenantId,
    isCustom: 1,
    seq: 1
  },
  compLabel: t('menu.type1'),
  // 校验规则
  formRules: {
    menuName: [
      {
        required: true,
        message: t('menu.name') + t('common.notEmpty'),
        trigger: ['blur', 'change']
      },
      {
        pattern: '[^ \x22]+',
        message: t('company.emptyMsg'),
        trigger: ['blur', 'change']
      }
    ],
    enName: [
      { required: true, message: t('common.enName') + t('common.notEmpty'), trigger: 'blur' }
    ],
    hkName: [
      { required: true, message: t('common.hkName') + t('common.notEmpty'), trigger: 'blur' }
    ],
    url: [{ required: true, message: t('menu.url') + t('common.notEmpty'), trigger: 'blur' }],
    status: { required: true, message: t('group.errStatusEmpty'), trigger: 'blur' }
  },
  parentMenus: [{}],
  menuNameField: 'menuName',
  typeOptions: [
    { value: 0, label: t('menu.type0') },
    { value: 1, label: t('menu.type1') },
    { value: 2, label: t('menu.type2') }
  ],
  clientTypeOptions: [
    { value: 1, label: 'PC' },
    { value: 2, label: t('menu.clientType2') },
    { value: 3, label: t('menu.clientType3') }
  ],
  loading: false
})
onMounted(async () => {
  //当前语言
  const curLang = localeStore.getCurrentLocale.lang
  if (curLang == 'en') {
    state.menuNameField = 'enName'
  } else if (curLang == 'zh_HK') {
    state.menuNameField = 'hkName'
  }
  init()
})

// 保存表单
const save = () => {
  formRef.value.validate(async (vaild) => {
    if (!vaild) {
      return
    }
    let form = Object.assign({}, state.formData)
    if (state.formData.menuType > 0 && state.formData.component.length == 0) {
      ElMessage.error(t('menu.type' + state.formData.menuType) + t('common.notEmpty'))
      return
    }
    state.loading = true
    await saveMenu(form).then((res) => {
      const result = res as any
      state.loading = false
      //保存成功
      if (result.success) {
        //刷新列表
        emitter.emit('MenuListRefresh')
        goBack()
      } else {
        ElMessageBox.alert(result.message)
      }
    })
  })
}
/**
 * @description 菜单类型改变后，修改component的Label
 * @author Elwin ZHANG
 * @date 2023-04-03 15:59
 */
const changeType = (event) => {
  if (event == 2) {
    state.compLabel = t('menu.type2')
  } else {
    state.compLabel = t('menu.type1')
  }
  if (event == 0) {
    state.formData.component = '#'
  } else {
    state.formData.component = ''
  }
}
// 返回列表
const goBack = () => {
  emitter.emit('closeTag', {
    closePath: currentRoute.value.fullPath,
    backPath: '/System/MenuList'
  })
}
/**
 * @description 当繁体中文为空时，转换简体中文为繁体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhHKAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //繁体中文为空时才自动转换
  if (state.formData.hkName.length > 0) {
    return
  }
  let data = (await getZhHKAndPinyin(text, 50)) as any
  state.formData.hkName = data.data.zhHK
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  formRef.value.clearValidate(['hkName', 'enName'])
}

/**
 * @description 当简体中文为空时，转换繁体中文为简体中文
 * @author Elwin ZHANG
 * @date 2023-03-21 10:33
 */
const zhCNAndPinyin = async (event) => {
  const text = event.target.value
  if (!text || text.length == 0) {
    return
  }
  //简体中文为空时才自动转换
  if (state.formData.menuName.length > 0) {
    return
  }
  let data = (await getZhCNAndPinyin(text, 50)) as any
  state.formData.menuName = data.data.zhCN
  //如果英文字段为空，默认为拼音
  if (state.formData.enName.length == 0) {
    state.formData.enName = data.data.pinyin
  }
  formRef.value.clearValidate(['menuName', 'enName'])
}

//渲染页面的接口
const init = async () => {
  const id = currentRoute.value.query.id as string
  const parentData = (await selectParentMenu(id)) as any
  state.parentMenus = parentData.data
  //修改
  if (id) {
    const data = (await getMenuById(id)) as any
    state.formData = data.data
    if (state.formData.menuType == 2) {
      state.compLabel = t('menu.type2')
    } else {
      state.compLabel = t('menu.type1')
    }
  }
}
</script>

<template>
  <div>
    <!-- 卡片表頭 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ $t('menu.info') }}</span>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="state.formData"
        :rules="state.formRules"
        class="demo-form-inline"
        label-position="left"
        label-width="150px"
        style="padding-right: 40px; padding-top: 10px"
      >
        <el-row :gutter="40">
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('menu.name')" prop="menuName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="state.formData.menuName"
                :placeholder="$t('common.inputText') + $t('menu.name')"
                maxlength="30"
                show-word-limit
                @blur="zhHKAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.hkName')" prop="hkName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="state.formData.hkName"
                :placeholder="$t('common.inputText') + $t('common.hkName')"
                maxlength="30"
                show-word-limit
                @blur="zhCNAndPinyin($event)"
              />
            </el-form-item>
            <el-form-item :label="$t('common.enName')" prop="enName" class="requireLabel">
              <el-input
                class="required_input"
                v-model="state.formData.enName"
                :placeholder="$t('common.inputText') + $t('common.enName')"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
            <el-form-item :label="$t('menu.type')" class="is-required requireLabel" prop="menuType">
              <el-select
                v-model="state.formData.menuType"
                class="m-2"
                :placeholder="$t('common.selectText')"
                size="default"
                style="margin: 0; position: relative; left: 10px"
                @change="changeType($event)"
                :disabled="state.formData.isCustom != 1"
              >
                <el-option
                  v-for="item in state.typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="state.compLabel" prop="component" class="normal_label">
              <el-input
                v-model="state.formData.component"
                :placeholder="$t('common.inputText') + state.compLabel"
                maxlength="100"
                show-word-limit
                :disabled="state.formData.isCustom != 1"
              />
            </el-form-item>
            <el-form-item
              :label="$t('menu.clientType')"
              class="is-required requireLabel"
              prop="frontType"
            >
              <el-select
                v-model="state.formData.frontType"
                class="m-2"
                :placeholder="$t('common.selectText')"
                size="default"
                style="margin: 0; position: relative; left: 10px"
                :disabled="state.formData.isCustom != 1"
              >
                <el-option
                  v-for="item in state.clientTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12">
            <el-form-item :label="$t('menu.url')" prop="url" class="requireLabel">
              <el-input
                class="required_input"
                v-model="state.formData.url"
                :placeholder="$t('common.inputText') + $t('menu.url')"
                minlength="2"
                maxlength="50"
                show-word-limit
                :disabled="state.formData.isCustom != 1"
              />
            </el-form-item>
            <el-form-item :label="$t('menu.params')" prop="params" class="normal_label">
              <el-input
                v-model="state.formData.params"
                :placeholder="$t('common.inputText') + $t('menu.params')"
                maxlength="100"
                show-word-limit
                :disabled="state.formData.isCustom != 1"
              />
            </el-form-item>
            <el-form-item :label="$t('menu.navUrl')" prop="navUrl" class="normal_label">
              <el-input
                v-model="state.formData.navUrl"
                :placeholder="$t('common.inputText') + $t('menu.navUrl')"
                maxlength="100"
                show-word-limit
                :disabled="state.formData.isCustom != 1"
              />
            </el-form-item>
            <el-form-item :label="$t('menu.icon')" prop="icon" class="normal_label">
              <el-input
                v-model="state.formData.icon"
                :placeholder="$t('common.inputText') + $t('menu.icon')"
                maxlength="100"
                show-word-limit
                style="width: 100%"
              >
                <template #append>
                  <el-link href="https://icon-sets.iconify.design/" target="_blank">
                    {{ $t('common.query') }}</el-link
                  >
                </template>
              </el-input>
            </el-form-item>
            <el-form-item :label="$t('menu.parentMenu')" prop="parentId" class="normal_label">
              <el-select
                v-model="state.formData.parentId"
                :placeholder="$t('common.selectText')"
                size="default"
                style="margin: 0; position: relative"
                :disabled="state.formData.isCustom != 1"
              >
                <el-option
                  v-for="item in state.parentMenus"
                  :key="item.id"
                  :label="item[state.menuNameField]"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('common.sort')" prop="sort" class="normal_label">
              <el-input-number
                :min="1"
                :max="999999"
                :step="10"
                v-model="state.formData.sort"
                :placeholder="$t('common.inputText') + $t('common.sort')"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="detailFooter">
        <el-button type="primary" plain @click="save" :loading="state.loading">
          <el-icon><Check /></el-icon>&nbsp;{{ $t('common.save') }}
        </el-button>
        <el-button type="info" plain @click="goBack">
          <el-icon><Close /></el-icon>&nbsp;{{ $t('common.giveUp') }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>
<style lang="less" scoped>
.box-card {
  .card-header {
    font-size: 16px;
    letter-spacing: 1px;
  }
  :deep(.el-input) {
    font-size: 12px;
  }
  :deep(.el-textarea__inner) {
    height: 85px;
    font-size: 12px;
  }
}
:deep(.el-input__inner) {
  &::placeholder {
    font-size: 12px;
  }
}
.el-select-dropdown__item {
  font-size: 12px;
}

.normal_label,
.required_input {
  position: relative;
  left: 10px;
}
:deep(.normal_label .el-form-item__error) {
  left: 0px;
}
:deep(.requireLabel .el-form-item__error) {
  margin-left: 10px;
}
</style>
